package com.tulele.vtool.service.impl;

import cn.hutool.core.date.DateTime;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tulele.vtool.mapper.*;
import com.tulele.vtool.model.*;
import com.tulele.vtool.model.combinedEntity.CombinedInvitedVipUserInfo;
import com.tulele.vtool.model.combinedEntity.CombinedLookArticleUserInfo;
import com.tulele.vtool.model.combinedEntity.UserArticleTailSwitchSet;
import com.tulele.vtool.model.combinedEntity.WxPushUserInfo;
import com.tulele.vtool.model.logEntity.PageDetailLog;
import com.tulele.vtool.model.logEntity.WantedUsers;
import com.tulele.vtool.model.logEntity.WantedUsersLog;
import com.tulele.vtool.service.ILookArticleInfoService;
import com.tulele.vtool.service.IUserInfoService;
import com.tulele.vtool.utils.*;
import com.tulele.vtool.wechat.service.WeixinService;
import com.tulele.vtool.wechat.service.WeixinServiceDL;
import com.tulele.vtool.wechat.service.WeixinServiceMap;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpUserBlacklistService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class UserInfoServiceImpl implements IUserInfoService {

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private WxNotifyMsgSetInfoMapper wxNotifyMsgSetInfoMapper;

    @Autowired
    private UserWithdrawLogInfoMapper withdrawLogInfoMapper;

    @Autowired
    private ILookArticleInfoService lookArticleInfoService;

    @Autowired
    private RedisCacheUtil redisCacheUtil;

    @Autowired
    private UserBrandInfoMapper userBrandInfoMapper;

    @Autowired
    private UserPromotionSettleInfoMapper userPromotionSettleInfoMapper;

    @Autowired
    private PageDetailLogMapper pageDetailLogMapper;


    @Override
    public UserInfo queryUserByUnionId(Integer userId, String wxUnionId, String openGroupCode) {
        return userInfoMapper.queryUserByUnionId(userId, wxUnionId, openGroupCode);
    }

    @Override
    public int activateUserByUnionId(Integer userId,
                                     Integer actUserId,
                                     String wxUnionId,
                                     String openGroupCode) {
        return userInfoMapper.activateUserByUnionId(userId, actUserId, wxUnionId, openGroupCode);
    }

    @Override
    public int cancelUserByUnionId(Integer userId, Integer cancelUserId, String wxUnionId, String openGroupCode) {
        return userInfoMapper.cancelUserByUnionId(userId, cancelUserId, wxUnionId, openGroupCode);
    }

    @Override
    public int replaceUserByUnionId(Integer userId, Integer replaceUserId, String wxUnionId, String openGroupCode) {
        return userInfoMapper.replaceUserByUnionId(userId, replaceUserId, wxUnionId, openGroupCode);
    }

    @Override
    public UserInfo getUserMainInfo(Integer userId) {
        return userInfoMapper.queryUserMainInfo(userId);
    }

    @Override
    public UserInfo queryUserMainInfoMine(Integer userId) {
        return userInfoMapper.queryUserMainInfoMine(userId);
    }

    @Override
    public int modifyUserNickName(UserInfo userInfo) {
        return userInfoMapper.updateUserInfo(userInfo);
    }

    @Override
    public int modifyUserSignature(UserInfo userInfo) {
        return userInfoMapper.updateUserInfo(userInfo);
    }

    @Override
    public int modifyUserQrcodeUrl(UserInfo userInfo) {
        return userInfoMapper.updateUserInfo(userInfo);
    }


    @Override
    public int modifyUserBillUrl(UserInfo userInfo) {
        return userInfoMapper.updateUserInfo(userInfo);
    }

    @Override
    public PageInfo<CombinedInvitedVipUserInfo> getInvitedVipUserInfo(Map<String, Object> queryMap) {
        int pageNum = (int) queryMap.get("pageNum");
        int pageSize = (int) queryMap.get("pageSize");

        PageHelper.startPage(pageNum, pageSize);
        List<CombinedInvitedVipUserInfo> invitedVipUserInfoList = userInfoMapper.queryInvitedVipUserInfo(queryMap);

        return new PageInfo<CombinedInvitedVipUserInfo>(invitedVipUserInfoList);
    }

    @Override
    public Integer getUserVipStatus(Integer userId) {
        return userInfoMapper.queryUserVipStatus(userId);
    }

    @Override
    public PageInfo<CombinedLookArticleUserInfo> getLookArticleUserInfo(Map<String, Object> queryMap) {
        int pageNum = (int) queryMap.get("pageNum");
        int pageSize = (int) queryMap.get("pageSize");

        int userId = (int) queryMap.get("userId");

        PageHelper.startPage(pageNum, pageSize);
        List<CombinedLookArticleUserInfo> userInfoList = lookArticleInfoService.getLookArticleUserInfo(userId);

        return new PageInfo<CombinedLookArticleUserInfo>(userInfoList);
    }

    @Override
    public UserInfo getUserBaseInfo(Integer userId) {
        return userInfoMapper.queryUserBaseInfo(userId);
    }

    @Override
    public Double getUserAccountBalance(Integer userId) {
        return userInfoMapper.queryUserAccountBalance(userId);
    }

    @Override
    public int addWxUserInfo(UserInfo userInfo) {
        return userInfoMapper.addUserInfo(userInfo);
    }

    @Override
    public Integer getUserStatusByOpenId(String openId) {
        return userInfoMapper.queryUserStatusByOpenId(openId);
    }

    @Override
    public int modifyWxUserInfo(UserInfo userInfo) {
        return userInfoMapper.updateUserInfo(userInfo);
    }

    @Override
    public int modifyUserVipStatus(UserInfo userInfo) {
        return userInfoMapper.updateUserInfo(userInfo);
    }

    @Override
    public Integer getUserReferer(Integer userId) {
        return userInfoMapper.queryUserReferer(userId);
    }

    @Override
    public int modifyUserAccountBalance(UserInfo userInfo) {
        return userInfoMapper.updateUserInfo(userInfo);
    }

    @Override
    public String getUserOpenId(Integer userId) {
        return userInfoMapper.queryUserOpenId(userId);
    }

    @Override
    public Integer addUserOpenIds(UserOpenIds userOpenIds) {
        return userInfoMapper.addUserOpenIds(userOpenIds);
    }

    @Override
    public int recordUserNotifySetInfo(WxNotifyMsgSetInfo wxNotifyMsgSetInfo) {

        //查询用户是否已经有了设置，有则修改，无则添加
        Integer userId = wxNotifyMsgSetInfo.getUserId();

        WxNotifyMsgSetInfo wxNotifyMsgSetInfoInDB = wxNotifyMsgSetInfoMapper.queryUserNotifySetInfo(userId);

        if (wxNotifyMsgSetInfoInDB != null) {

            wxNotifyMsgSetInfo.setId(wxNotifyMsgSetInfoInDB.getId());
            wxNotifyMsgSetInfo.setModifyTime(DateUtil.getCurDate());

            return wxNotifyMsgSetInfoMapper.updateUserNotifySetInfo(wxNotifyMsgSetInfo);

        } else {

            wxNotifyMsgSetInfo.setCreateTime(DateUtil.getCurDate());
            return wxNotifyMsgSetInfoMapper.addUserNotifySetInfo(wxNotifyMsgSetInfo);

        }
    }

    @Override
    public int updateUserNotifySetInfo(WxNotifyMsgSetInfo wxNotifyMsgSetInfo) {
        return wxNotifyMsgSetInfoMapper.updateUserNotifySetInfo(wxNotifyMsgSetInfo);
    }

    @Override
    public WxNotifyMsgSetInfo getUserNotifySetInfo(Integer userId) {
        return wxNotifyMsgSetInfoMapper.queryUserNotifySetInfo(userId);
    }

    @Override
    public int modifyUserTelNum(UserInfo userInfo) {
        return userInfoMapper.updateUserInfo(userInfo);
    }

    @Override
    public int modifyUserJobPosition(UserInfo userInfo) {
        return userInfoMapper.updateUserInfo(userInfo);
    }

    @Override
    public int modifyUserCompany(UserInfo userInfo) {
        return userInfoMapper.updateUserInfo(userInfo);
    }

    @Override
    public Integer getUserConcernStatus(Integer userId) {
        return userInfoMapper.queryUserConcernStatus(userId);
    }

    @Override
    public Integer getUserConcernStatus_gzhdbjssq(Integer userId, String gzhCode) {
        return userInfoMapper.queryUserConcernStatus_gzhdbjssq(userId, gzhCode);
    }

    @Override
    public Integer getUserConcernStatus_zktdb(Integer userId, String gzhCode) {
        return userInfoMapper.queryUserConcernStatus_zktdb(userId, gzhCode);
    }

    @Override
    public UserInfo getUserBaseInfoByOpenId(String openId) {
        return userInfoMapper.queryUserBaseInfoByOpenId(openId);
    }

    @Override
    public int modifyWithdrawInfo(UserWithdrawLogInfo userWithdrawLogInfo) {
        return withdrawLogInfoMapper.updateWithdrawInfo(userWithdrawLogInfo);
    }

    @Override
    public List<UserInfo> getInvitedUserInfo(int userId) {
        List<UserInfo> invitedUserInfoList = userInfoMapper.queryInvitedUserInfo(userId);

        return invitedUserInfoList;
    }

//    @Override
//    public PageInfo<UserInfo> getInvitedUserInfoPage_gjhkpt(int userId, int pageNum, int pageSize) {
//        PageHelper.startPage(pageNum, pageSize);
//        List<UserInfo> invitedUserInfoList_gjhkpt = getInvitedUserInfo_gjhkpt(userId);
//        List<UserInfo> invitedUserInfoList = invitedUserInfoList_gjhkpt.stream()
//                .distinct()
//                .sorted(Comparator.comparing(UserInfo::getCommissionLevel, Comparator.nullsFirst(Integer::compareTo)).reversed())
//                .collect(Collectors.toList());
//
//        return new PageInfo<UserInfo>(invitedUserInfoList);
//    }

    @Override
    public List<UserInfo> getInvitedUserInfo_gjhkpt(int userId) {
        List<UserInfo> invitedUserInfoList = userInfoMapper.queryInvitedUserInfo(userId);

        if (invitedUserInfoList != null && invitedUserInfoList.size() > 0) {
            Integer size = invitedUserInfoList.size();

            for (int i = 0; i < size; i++) {
                UserInfo ue = invitedUserInfoList.get(i);
                ue.setCommissionLevelTxt(getUserVipLevel(ue.getUserId()));
                if (ue.getCommissionLevelTxt().equals(SysConstant.COMMISSION_LEVEL_4)) {
                    ue.setCommissionLevel(4);
                } else if (ue.getCommissionLevelTxt().equals(SysConstant.COMMISSION_LEVEL_3)) {
                    ue.setCommissionLevel(3);
                } else if (ue.getCommissionLevelTxt().equals(SysConstant.COMMISSION_LEVEL_2)) {
                    ue.setCommissionLevel(2);
                } else {
                    ue.setCommissionLevel(1);
                }
//                List<UserInfo> invitedUserInfoList_sub = getInvitedUserInfo_gjhkpt(ue.getUserId());
//                if (invitedUserInfoList_sub != null && invitedUserInfoList_sub.size() > 0) {
//                    invitedUserInfoList.addAll(invitedUserInfoList_sub);
//                }
            }
        }

        return invitedUserInfoList.stream().sorted(Comparator.comparing(UserInfo::getCommissionLevel, Comparator.nullsFirst(Integer::compareTo)).reversed())
                .collect(Collectors.toList());
    }

    @Override
    public List<UserInfo> getInvitedUserInfobyPage(Integer userId, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<UserInfo> invitedUserInfoList = userInfoMapper.queryInvitedUserInfo(userId);

        return invitedUserInfoList;
    }


    @Override
    public Integer getInvitedRegUserCount(Integer userId) {
        return userInfoMapper.queryInvitedRegUserCount(userId);
    }

    @Override
    public Integer getUserValidNotifySetStatus(Integer userId) {
        return wxNotifyMsgSetInfoMapper.queryUserValidNotifySetStatus(userId);
    }

    @Override
    public UserInfo getUserSubTimeRelationInfo(Integer userId) {
        return userInfoMapper.queryUserSubTimeRelationInfo(userId);
    }

    @Override
    public int modifyUserAvatar(UserInfo userInfo) {
        return userInfoMapper.updateUserInfo(userInfo);
    }

    @Override
    public List<UserInfo> getNotVipUsers(String gzhCode) {
        return userInfoMapper.getNotVipUsers(gzhCode);
    }

    ;

    @Override
    public List<UserInfo> getNotReferer(String gzhCode) {
        return userInfoMapper.getNotReferer(gzhCode);
    }

    ;

    @Override
    public List<UserInfo> queryByNickName(String gzhCode, String nickName) {
        return userInfoMapper.queryByNickName(gzhCode, nickName);
    }

    @Override
    public List<UserInfo> queryWantedByNickName(String nickName) {
        return userInfoMapper.queryWantedByNickName(nickName);
    }

    @Override
    public boolean updateUserBillByUserId(Integer userId) {
        UserInfo userInfo = userInfoMapper.queryUserMainInfo(userId);
        if (null == userInfo) {
            return false;
        }
        userInfo.setBillUrl("");
        return userInfoMapper.updateUserInfo(userInfo) == 1;
    }

    @Override
    public boolean updateUserQrCodeByUserId(Integer userId) {
        UserInfo userInfo = userInfoMapper.queryUserMainInfo(userId);
        if (null == userInfo) {
            return false;
        }
        userInfo.setQrcodeUrl("");
        return userInfoMapper.updateUserInfo(userInfo) == 1;
    }

    @Override
    public List<UserInfo> selectUserList(Integer pageNum, Integer pageSize, Integer userId, String gzhCode, String[] screen, List<Integer> needIds, List<Integer> articleTypeIds) {
        //  PageHelper.startPage(pageNum, pageSize);
        return this.userInfoMapper.selectUserList(userId, gzhCode, screen, needIds, articleTypeIds);
    }

    @Override
    public String selectRegionByUserId(Integer userId) {
        return this.userInfoMapper.selectRegionByUserId(userId);
    }

    @Override
    public Integer selectCountRegionByUserId(Integer userId) {
        return this.userInfoMapper.selectCountRegionByUserId(userId);
    }

    @Override
    public void addRegionByUserId(Integer userId, UserRegionInfo userRegionInfo, String gzhCode) {
        userRegionInfo.setUserId(userId);
        userRegionInfo.setGzhCode(gzhCode);
        String[] screen = null;
        if (StringUtils.isNotBlank(userRegionInfo.getRegion())) {
            screen = StringUtils.split(userRegionInfo.getRegion(), ',');
        }
        if (null != screen && screen.length == 1) {
            userRegionInfo.setProvince(screen[0]);
        }
        if (null != screen && screen.length == 2) {
            userRegionInfo.setProvince(screen[0]);
            userRegionInfo.setCity(screen[1]);
        }
        if (null != screen && screen.length == 3) {
            userRegionInfo.setProvince(screen[0]);
            userRegionInfo.setCity(screen[1]);
            userRegionInfo.setDistrict(screen[2]);
        }
        // 查询是否存在地址
        Integer region = this.userInfoMapper.selectCountRegionByUserId(userId);
        // 如果存在就修改
        if (region.equals(1) && null != region) {
            userRegionInfo.setModifyTime(DateUtil.getCurDate());
            this.userInfoMapper.updateRegionByUserId(userRegionInfo);
        } else {
            // 如果不存在就添加
            userRegionInfo.setCreateTime(DateUtil.getCurDate());
            this.userInfoMapper.addRegionByUserId(userRegionInfo);
        }

    }

    @Override
    public void addRegion(UserRegionInfo userRegionInfo) {
        // 查询是否存在地址
        Integer region = this.userInfoMapper.selectCountRegionByUserId(userRegionInfo.getUserId());
        // 如果存在就修改
        if (region.equals(1) && null != region) {
            userRegionInfo.setModifyTime(DateUtil.getCurDate());
            this.userInfoMapper.updateRegionByUserId(userRegionInfo);
        } else {
            // 如果不存在就添加
            userRegionInfo.setCreateTime(DateUtil.getCurDate());
            this.userInfoMapper.addRegionByUserId(userRegionInfo);
        }

    }

    @Override
    public List<UserInfo> selectUserListByRandom(Integer pageNum, Integer pageSize, Integer userId, String gzhCode, String[] screen, List<Integer> needIds, List<Integer> articleTypeIds, Integer standardUserById) {
        /* PageHelper.startPage(pageNum, pageSize);*/
        Integer start = (pageNum - 1) * pageSize;
        Integer number = pageSize;
        return this.userInfoMapper.selectUserListByRandom(userId, gzhCode, screen, needIds, articleTypeIds, start, number, standardUserById);
    }

    @Override
    public Integer selectStandardUserIdByCreationTimeDesc() {
        return this.userInfoMapper.selectStandardUserIdByCreationTimeDesc();
    }

    /**
     * 更新人脉广场最后活跃时间
     *
     * @param userId
     * @return
     */
    @Override
    public boolean updateLastConActiveTimeByUserId(Integer userId) {
        UserInfo userInfo = userInfoMapper.queryUserMainInfo(userId);
        if (null == userInfo) {
            return false;
        }
        userInfo.setLastConactiveTime(DateUtil.getCurDate());
        return userInfoMapper.updateUserInfo(userInfo) == 1;
    }

    @Override
    public UserInfo getUserInfo(Integer userId) {
        return userInfoMapper.queryUserInfo(userId);
    }

    @Override
    public int setBlockState(Integer userId) {
        blockLinkByUser(userId, 1);
        return userInfoMapper.setBlockState(userId);
    }

    /**
     * @param userId        用户 userId
     * @param blockLinkType 操作类型 1-拉入黑名单 2-拉出黑名单
     * @return
     */
    @Override
    public int blockLinkByUser(Integer userId, Integer blockLinkType) {
        if (userId == null || blockLinkType == null) {
            return 0;
        }

        UserInfo userInfo = userInfoMapper.queryUserMainInfo(userId);

        if (userInfo != null && userInfo.getOpenId() != null) {
            try {
                String gzhCode = userInfo.getGzhCode();
                String openId = userInfo.getOpenId();

                WeixinServiceDL weixinService = WeixinServiceMap.getWeixinService(gzhCode);
                WxMpUserBlacklistService blackListService = weixinService.getBlackListService();
                List<String> var1 = new ArrayList();
                var1.add(openId);
                if (blockLinkType == 1) {
                    blackListService.pushToBlacklist(var1);
                }

                if (blockLinkType == 2) {
                    blackListService.pullFromBlacklist(var1);
                }

            } catch (WxErrorException e) {
                e.printStackTrace();
            }
        }

        return 1;
    }

    @Override
    public Integer getCardStyle(Integer userId) {
        return userInfoMapper.getCardStyle(userId);
    }

    @Override
    public boolean setCardStyle(Integer userId, Integer cardStyle) {
        return userInfoMapper.setCardStyle(userId, cardStyle);
    }

    @Override
    public UserInfo queryUserByUnionIdAndGzhCode2(String unionId, String gzhCode) {
        return userInfoMapper.queryUserByUnionIdAndGzhCode2( unionId,gzhCode);
    }

    @Override
    public Integer showVipByUserId(Integer userId) {
        return userInfoMapper.showVipByUserId(userId);
    }

    @Override
    public int getUserCountByGzhCode(String gzhCode) {
        return userInfoMapper.getUserCountByGzhCode(gzhCode);
    }

    @Override
    public List<UserInfo> getUserInfoByGzhCode(String gzhCode, int offset, int pageSize) {
        return userInfoMapper.getUserInfoByGzhCode(gzhCode, offset, pageSize);
    }

    @Override
    public List<UserInfo> getUserInfoByGzhCode2(String gzhCode) {
        return userInfoMapper.getUserInfoByGzhCode2(gzhCode);
    }

    @Override
    public int updateOpenidByUserId(Integer userId, String newOpenId) {
        Integer affectedRows = userInfoMapper.updateOpenidByUserId(userId, newOpenId);
        return affectedRows == null ? 0 : affectedRows.intValue();
    }

    @Override
    public int updateOpenidByOpenId(String oldOpenId, String newOpenId) {
        Integer affectedRows = userInfoMapper.updateOpenidByOpenId(oldOpenId, newOpenId);
        return affectedRows == null ? 0 : affectedRows.intValue();
    }

    @Override
    public int updateUserGroupOpenId(String gzhCode, String oldOpenId, String newOpenId) {
        Integer affectedRows = userInfoMapper.updateUserGroupOpenId(gzhCode, oldOpenId, newOpenId);
        return affectedRows == null ? 0 : affectedRows.intValue();
    }

    @Override
    public int updateOpenidByGzhCode(String gzhCode, String oriOpenid, String newOpenid) {
        Integer affectedRows = userInfoMapper.updateOpenidByGzhCode(gzhCode, oriOpenid, newOpenid);
        return affectedRows == null ? 0 : affectedRows.intValue();
    }

    @Override
    public String getUserVipLevel(Integer userId) {
        int firstLevelProportion = 0;
        int secondLevelProportion = 0;
        int thirdLevelProportion = 0;
        int fourthLevelProportion = 0;
        int fifthLevelProportion = 0;

        UserPromotionSettleInfo userPromotionSettleInfo = userPromotionSettleInfoMapper.queryUserPromotionSettleInfo(userId);
        if (userPromotionSettleInfo != null) {
            firstLevelProportion = Optional.ofNullable(userPromotionSettleInfo.getFirstLevelProportion()).orElse(0);// 一级
            secondLevelProportion = Optional.ofNullable(userPromotionSettleInfo.getSecondLevelProportion()).orElse(0);// 二级
            thirdLevelProportion = Optional.ofNullable(userPromotionSettleInfo.getThirdLevelProportion()).orElse(0);// 三级
            fourthLevelProportion = Optional.ofNullable(userPromotionSettleInfo.getFourthLevelProportion()).orElse(0);// 四级
            fifthLevelProportion = Optional.ofNullable(userPromotionSettleInfo.getFifthLevelProportion()).orElse(0);// 五级
        }

        String vipLevel = SysConstant.COMMISSION_LEVEL_1;// 高级会员 只开1级（默认）
        if (firstLevelProportion > 0 && secondLevelProportion > 0 && thirdLevelProportion > 0 && (fourthLevelProportion > 0 || fifthLevelProportion > 0)) {
            vipLevel = SysConstant.COMMISSION_LEVEL_4;// 总裁 - 开4级
        } else if (firstLevelProportion > 0 && secondLevelProportion > 0 && thirdLevelProportion > 0 && fourthLevelProportion == 0 && fifthLevelProportion == 0) {
            vipLevel = SysConstant.COMMISSION_LEVEL_3;// 总监 - 开3级
        } else if (firstLevelProportion > 0 && secondLevelProportion > 0 && thirdLevelProportion == 0 && fourthLevelProportion == 0 && fifthLevelProportion == 0) {
            vipLevel = SysConstant.COMMISSION_LEVEL_2;// 经理 - 开2级
        }
        return vipLevel;
    }

    @Override
    public int getUserTeamMemberCount(String gzhCode) {
        return userInfoMapper.getUserTeamMemberCount(gzhCode);
    }

    @Override
    public int getUserBlockState(Integer userId) {
        Integer userBlockState = Optional.ofNullable(userInfoMapper.getUserBlockState(userId)).orElse(0);
        return userBlockState.intValue();
    }

    @Override
    public void recordAccessBlockPage(Integer userId, String gzhCode) {
        PageDetailLog pageDetailLog = new PageDetailLog();
        pageDetailLog.setUserId(userId);
        pageDetailLog.setGzhCode(gzhCode);
        pageDetailLog.setPageName("拉黑页");
        pageDetailLog.setAccessTime(DateUtil.getCurDate());

        pageDetailLogMapper.addPageAccess(pageDetailLog);
    }

    @Override
    public int getSubordinateCount(Integer userId) {
        return userInfoMapper.getSubordinateCount(userId);
    }

    @Override
    public List<Integer> getFirstLevelUser(String gzhCode) {
        return userInfoMapper.getFirstLevelUser(gzhCode);
    }

    @Override
    public List<Integer> getSecondLevelUser(String gzhCode) {
        return userInfoMapper.getSecondLevelUser(gzhCode);
    }

    @Override
    public int getVipUserCount(String gzhCode, List<Integer> userIds) {
        return userInfoMapper.getUserCountByVipStatus(gzhCode, userIds, 1);
    }

    @Override
    public int getUnVipUserCount(String gzhCode, List<Integer> userIds) {
        return userInfoMapper.getUserCountByVipStatus(gzhCode, userIds, 0);
    }

    @Override
    public List<UserInfo> getUserSubUserList(Integer userId, String nickName) {
        return userInfoMapper.queryInvitedUserInfoByNickName(userId, nickName);
    }

    @Override
    public UserArticleTailSwitchSet getUserArticleTailSwitchSet(Integer userId) {
        return wxNotifyMsgSetInfoMapper.queryUserArticleTailSwitch(userId);
    }

    @Override
    public int updateUserArticleTailSwitchSet(Integer userId, UserArticleTailSwitchSet userArticleTailSwitchSet) {
        return wxNotifyMsgSetInfoMapper.updateUserArticleTailSwitchSet(userId, userArticleTailSwitchSet.getAdvertSwitchStatus(), userArticleTailSwitchSet.getTableSwitchStatus());
    }

    @Override
    public UserInfo getUserByImg(String gzhCode, String nickName, String imgPath, Integer targetUserId) throws Exception {
        List<UserInfo> userInfos = userInfoMapper.queryByNickName(gzhCode, nickName);

        if (userInfos != null && userInfos.size() > 0) {
            UserInfo targetUser = userInfoMapper.queryUserMainInfo(targetUserId);

            if (targetUser != null && targetUser.getAvatarUrl() != null) {

                String tarAvatarName = UUID.randomUUID().toString() + ".jpg";

                ToolUtil.downloadAvatarPic(targetUser.getAvatarUrl(), targetUser.getUserId(), tarAvatarName, SysConstant.WX_AVATAR_DOWNLOAD_PATH2);

                String tarAvatarPath = SysConstant.WX_AVATAR_DOWNLOAD_PATH2 + targetUser.getUserId() + "/" + tarAvatarName;
                String tarHashCode = SimilarImageSearch.produceFingerPrint(tarAvatarPath);

                for (UserInfo wu : userInfos) {
                    String avatarName = UUID.randomUUID().toString() + ".jpg";
                    ToolUtil.downloadAvatarPic(wu.getAvatarUrl(), wu.getUserId(), avatarName, SysConstant.WX_AVATAR_DOWNLOAD_PATH2);
                    String avatarPath = SysConstant.WX_AVATAR_DOWNLOAD_PATH2 + wu.getUserId() + "/" + avatarName;
                    String hashCode = SimilarImageSearch.produceFingerPrint(avatarPath);

                    int difference = SimilarImageSearch.hammingDistance(tarHashCode, hashCode);
                    FileUtils.forceDeleteOnExit(new File(avatarPath));
                    if (difference == 0) {
                        FileUtils.forceDeleteOnExit(new File(tarAvatarPath));
                        copyUserInfo(wu, targetUser);
                        return wu;
                    }
                }
                FileUtils.forceDeleteOnExit(new File(tarAvatarPath));
            }
        }

        return null;
    }

    @Override
    public void copyUserInfo(UserInfo formerUser, UserInfo targetUser) {

        //先把资料复制过来
        if (targetUser != null && formerUser != null) {

            //复制基本信息
            UserInfo curUserInfo = new UserInfo();
            curUserInfo.setUserId(targetUser.getUserId());
            curUserInfo.setSignature(formerUser.getSignature());
            curUserInfo.setQrcodeUrl(formerUser.getQrcodeUrl());
            curUserInfo.setGender(formerUser.getGender());
            curUserInfo.setReferer(formerUser.getReferer());
            curUserInfo.setAccountBalance(formerUser.getAccountBalance());
            curUserInfo.setCommissionBalance(formerUser.getCommissionBalance());
            curUserInfo.setTelNum(formerUser.getTelNum());
            curUserInfo.setVipStatus(formerUser.getVipStatus());
            curUserInfo.setModifyTime(new Date());
            curUserInfo.setLastActiveTime(new Date());
            userInfoMapper.updateUserInfo(curUserInfo);

            //复制推荐人品牌
            userBrandInfoMapper.copyRefererBrand(targetUser.getUserId(), formerUser.getUserId());
        }
    }

    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public Integer updateUserIdByUnionId(WxMpUser userWxInfo, Integer finalUserId, String souGzhCode, String trgGzhCode) {
        try {

            Integer vipStatus = userInfoMapper.queryUserVipStatus(finalUserId);
            if(vipStatus == null || vipStatus == 0) { //不是会员才导流 20210816

                if (userWxInfo.getUnionId() != null && userWxInfo.getUnionId().trim().length() > 0) {
                    //log.info("[SubscribeHandler]_subBrandInfo_openGroupCode:" + openGroupCode);
                    UserInfo actUser = userInfoMapper.queryUserByUnionIdAndGzhCode(finalUserId, userWxInfo.getUnionId(), souGzhCode);//先去源号找到 对应的 记录
                    //log.info("[SubscribeHandler]_subBrandInfo_queryUserByUnionId:" + actUser);
                    if (actUser != null && actUser.getUserId() > 0) {
                        //log.error("updateUserIdByUnionId_finalUserId:" + actUser.getUserId());

                        //先把资料复制过来
                        UserInfo curUserInfo = new UserInfo();
                        curUserInfo.setUserId(finalUserId);
                        curUserInfo.setSignature(actUser.getSignature());
                        curUserInfo.setAvatarUrl(actUser.getAvatarUrl());
                        curUserInfo.setQrcodeUrl(actUser.getQrcodeUrl());
                        curUserInfo.setGender(actUser.getGender());
                        curUserInfo.setReferer(actUser.getReferer());
                        curUserInfo.setAccountBalance(actUser.getAccountBalance());
                        curUserInfo.setCommissionBalance(actUser.getCommissionBalance());
                        curUserInfo.setTelNum(actUser.getTelNum());
                        curUserInfo.setVipStatus(actUser.getVipStatus());
                        curUserInfo.setConcernStatus(actUser.getConcernStatus());
                        curUserInfo.setModifyTime(new Date());
                        curUserInfo.setLastActiveTime(new Date());
                        modifyWxUserInfo(curUserInfo);

                        Integer actUserId = actUser.getUserId();//源号 用户ID
                        //log.error("updateUserIdByUnionId_actUserId:" + actUserId);
                        Integer cancelUserId = Math.abs(actUser.getUserId()) * -1;//把活跃Id设置为负
                        //log.error("updateUserIdByUnionId_cancelUserId:" + cancelUserId);
                        int v_cancel = userInfoMapper.cancelUserByUnionIdAndGzhCode(actUserId, cancelUserId, userWxInfo.getUnionId(), souGzhCode);//把源号的userid 处理掉
                        //log.info("[SubscribeHandler]_subBrandInfo_cancelUserByUnionId_v_cancel:" + v_cancel);
                        if (v_cancel > 0) {
                            int v_act = userInfoMapper.activateUserByUnionIdAndGzhCode(finalUserId, actUserId, userWxInfo.getUnionId(), trgGzhCode);//再把 目标号的userid 更换一下
                            //log.info("[SubscribeHandler]_subBrandInfo_activateUserByUnionId_v_act:" + v_act);
                            if (v_act > 0) {
                                //replaceUserByUnionId(cancelUserId, finalUserId, userWxInfo.getUnionId(), openGroupCode.trim());

                                //设置接收消息推送缓存(活跃的)
                                WxPushUserInfo wxPushUserInfoCal = new WxPushUserInfo();
                                wxPushUserInfoCal.setUserId(actUserId);
                                wxPushUserInfoCal.setOpenId(actUser.getOpenId());
                                wxPushUserInfoCal.setCacheTime(DateTime.now().toString("yyyy-MM-dd HH:mm:ss"));
                                redisCacheUtil.setCacheObject("wxPushUser" + actUserId, JSON.toJSONString(wxPushUserInfoCal), 172800);

                                redisCacheUtil.removeSingleCache("wxPushUser" + finalUserId);//删除取消的

                                return actUserId;
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            //log.error("[SubscribeHandler]_subBrandInfo_activateUserByUnionId_error:" + e.getMessage());
        }
        return finalUserId;
    }
}
